package com.shangye.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class HttpServletRequest {

    private Socket socket;
    private String method;
    private String uri;
    private String protocol;

    private Map<String ,String> headers = new HashMap<>();

    public HttpServletRequest(Socket socket) throws IOException{

        this.socket = socket;

        parseRquestLine();
        parseHeaders();
        parseContent();


    }


    private void parseRquestLine() throws IOException{
        String line = redLine();
        System.out.println("请求行：" + line);

        String[] data = line.split("\\s");
        method = data[0];
        uri = data[1];
        protocol = data[2];

        System.out.println("请求方式：" + method);
        System.out.println("请求路径：" + uri);
        System.out.println("协议版本：" + protocol);

    }
    private void parseHeaders()throws IOException{
        while (true){
            String line = redLine();
            if (line.isEmpty()){
                break;
            }
            System.out.println("消息头：" + line);
            String[] split = line.split(":\\s");
            headers.put(split[0],split[1]);
        }
        System.out.println("headers:" +headers);
    }
    private void parseContent(){}



    private String redLine() throws IOException {
        InputStream inputStream = socket.getInputStream();
        int d;
        StringBuilder builder = new StringBuilder();
        char pre = 'a',cur = 'a';
        while ((d = inputStream.read())!=-1){
            cur = (char)d;
            if (pre==13&&cur==10){
                break;
            }
            pre = cur;
            builder.append(pre);
        }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHeaders(String key) {
        return headers.get(key);
    }
}
